package org.geometerplus.zlibrary.core.view;

import android.graphics.Bitmap;
import android.graphics.Path;

import com.chineseall.reader.ui.ReadRenderSetting;

import org.geometerplus.fbreader.fbreader.FBReaderApp;
import org.geometerplus.zlibrary.ui.android.view.ZLAndroidPaintContext;

/**
 * Created by Loy on 16-2-6.
 * zwsc
 */
public class SelectionTipBox {

    private final static Path mPath = new Path();
    private static Bitmap clipBitmap = null;
    private synchronized final static Bitmap getClipBitmap(int centerX, int centerY, int maxWidth, int maxHeight) {
        FBReaderApp fbReaderApp = (FBReaderApp) FBReaderApp.Instance();
        if(clipBitmap == null || clipBitmap.isRecycled())
        {
            clipBitmap = null;
        }
        else if(clipBitmap.getWidth()  != maxHeight || clipBitmap.getHeight() != maxHeight)
        {
            clipBitmap.recycle();
            clipBitmap = null;
        }

        if(clipBitmap == null)
        {
            clipBitmap = Bitmap.createBitmap(maxWidth, maxHeight, Bitmap.Config.ARGB_8888);
        }
        ZLAndroidWidget widget = (ZLAndroidWidget) fbReaderApp.getViewWidget();
        widget.drawCurrentPageOnBitmap(clipBitmap, centerX, centerY);
        return clipBitmap;
    }
    public static void draw(ZLAndroidPaintContext context, int x, int y)
    {

        Bitmap maskBitmap = ReadRenderSetting.getInstance().getSelectionBoxMaskBmp();
        if (maskBitmap == null) {
            return;
        }
        Bitmap clipBitmap = getClipBitmap(x, y, maskBitmap.getWidth(), maskBitmap.getHeight());

        int offsetX = 0, offsetY = 0;
        offsetX = x - maskBitmap.getWidth() / 2;
        y -= 80;
        offsetY = y - maskBitmap.getHeight() / 2;
        if(offsetX < 0)
        {
            offsetX = 0;
        }
        else if(offsetX + maskBitmap.getWidth() > context.getWidth())
        {
            offsetX = context.getWidth() - maskBitmap.getWidth();
        }

        if(offsetY < 0)
        {
            offsetY = 0;
        }
        else if(offsetY + maskBitmap.getHeight() > context.getHeight())
        {
            offsetY = context.getHeight() - maskBitmap.getHeight();
        }
        mPath.reset();
        mPath.addCircle(offsetX + maskBitmap.getWidth() / 2, offsetY + maskBitmap.getHeight() / 2, maskBitmap.getWidth() / 2 - 7, Path.Direction.CW);
        context.save();
        context.clip(mPath);

        context.drawBitmap(offsetX, offsetY, clipBitmap);
        context.restore();
        context.save();
        mPath.reset();
        mPath.addCircle(offsetX + maskBitmap.getWidth() / 2, offsetY + maskBitmap.getHeight() / 2,  maskBitmap.getWidth() / 2, Path.Direction.CW);
        context.save();
        context.clip(mPath);
        context.drawBitmap(offsetX, offsetY, maskBitmap);
        context.restore();
    }

}
